package com.jinbiao.quasar.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.jinbiao.quasar.annotate.OperationLog;
import com.jinbiao.quasar.constant.Constant;
import com.jinbiao.quasar.constant.RedisBucketKey;
import com.jinbiao.quasar.dto.MenuDto;
import com.jinbiao.quasar.dto.OnlineUserDto;
import com.jinbiao.quasar.dto.UserMenuDto;
import com.jinbiao.quasar.model.SysButton;
import com.jinbiao.quasar.model.SysMenu;
import com.jinbiao.quasar.model.SysUser;
import com.jinbiao.quasar.model.SysUserOnline;
import com.jinbiao.quasar.util.AjaxJson;
import com.jinbiao.quasar.util.RedisUtil;
import org.noear.solon.annotation.Controller;
import org.noear.solon.annotation.Mapping;
import org.noear.solon.extend.sqltoy.annotation.Db;
import org.sagacity.sqltoy.dao.SqlToyLazyDao;
import org.sagacity.sqltoy.model.EntityQuery;
import org.sagacity.sqltoy.model.Page;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Controller
@OperationLog
public class UserOnlineController {
    @Db
    SqlToyLazyDao dao;

    @Mapping("/user-online/get-user-online-list")
    public AjaxJson getUserOnlineList(int page,int pageSize) {
        Page<OnlineUserDto> pageResult =  dao.findPageBySql(new Page(pageSize,page),"sysUserOnlineList",new OnlineUserDto());
        pageResult.getRows().stream().forEach(item->{
            String id = (String) StpUtil.getLoginIdByToken(item.getToken());
            String userStr = RedisUtil.getClient().getBucket().get(RedisBucketKey.USER+id);
            item.setUser(JSONUtil.toBean(userStr,SysUser.class));
        });
        return AjaxJson.getSuccessData(pageResult);
    }

    @Mapping("/user-online/kick-online-user")
    public AjaxJson kickOnlineUser(String username){
        if(StrUtil.isNotEmpty(username)) {
            List<SysUser> sysUsers = dao.findBySql("sysUserList", new SysUser(username));
            if(CollectionUtil.isNotEmpty(sysUsers)) {
                SysUser kickUser = sysUsers.get(0);
                StpUtil.kickout(kickUser.getId());
                dao.deleteByQuery(SysUserOnline.class, EntityQuery.create().where("username=?").values(username));
                return AjaxJson.getSuccess("踢出用户成功");
            }
            return AjaxJson.getError("传递用户信息错误，踢出用户失败");
        }else{
            return AjaxJson.getError("传递用户信息错误，踢出用户失败");
        }

    }

}
